package com.cy.pj.module.controller;


import com.cy.pj.module.pojo.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class HealthController {//Handler(通过此对象处理DispatcherServlet分发过来的请求)

    @RequestMapping("doGetResponse")
    @ResponseBody
    public ResponseResult doGetResponse(){
        ResponseResult rs=new ResponseResult();
        rs.setCode(200);
        rs.setMessage("OK");
        return rs;
    }

    //返回页面
    @RequestMapping("doHealthUI")
    public String doHealthUI(){
        return "default";
    }

    //返回数据和页面
    @RequestMapping("/doHealth")//spring，此方法由DispatcherServlet对象通过反射调用
    public ModelAndView doHealth(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("default");//viewname
        mv.addObject("username","chenzishu");
        mv.addObject("state","亚健康");
        //return "default";//viewname
        return mv;
        //1.返回值会交给DispatcherServlet对象进行处理
        //2.DispatcherServlet对象会调用viewresolver对结果进行解析
        //2.1基于viewname找到对应的view页面（prefix+viewname+suffix）
        //2.2将model中的数据填充到view页面上
        //2.3返回一个带有module数据的页面给DispatcherServlet
        //3.DispatcherServlet将带有model数据的页面响应到客户端


        /*public String doHealth(Model model){
            model.addAttribute("username","zhangjiuyjun");
            model.addAttribute("state","true");
        }
        return "default";
        配置thymeleaf的前缀
        spring.thymeleaf.prefix=classpath:/templates/health
        */
    }
    //返回数据
    @RequestMapping("/health.html")
    @ResponseBody//当使用此注解描述控制层方法时，用于告诉spring框架，这个方法返回值尽量转换为json串响应到客户端
    //将转换以后的结果写到response对象的响应体中
    //方法的返回值不在封装为ModelAndview对象，不会再交给解析器进行解析，而是直接基于response对象响应到客户端
    public Map<String,Object> doHealth1(){
        Map<String,Object> map=new HashMap<>();
        map.put("username","tony");
        map.put("state",true);
        return map;
    }

    @RequestMapping("/doPrint")
    //@ResponseBody//是告诉springmvc这个方法不再封装成ModelAndview而是按照一定格式写到response对象的响应体中
    public void doPrint(HttpServletResponse response)throws Exception{
        Map<String,Object> map=new HashMap<>();
        map.put("username","刘德华");
        map.put("state",true);
        //将map中的数据转换为json格式字符串
        ObjectMapper om=new ObjectMapper();
        String jsonStr= om.writeValueAsString(map);
        System.out.println("jsonStr="+jsonStr);
        //将字符串响应到客户端
        //设置响应数据的编码
        response.setCharacterEncoding("utf-8");
        //告诉客户端要向它响应的数据类型为text/html，编码为utf-8，请以这种编码进行数据呈现
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(jsonStr);
    }
}
